package vue;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;

import controleur.ControllerSimulation;
import java.awt.Font;
import metier.Element;
import metier.Fourmiliere;
import metier.Nouriturre;
import utiles.FourmizLogger;

public class VueSimulation extends FourmizFrame {

    private JPanel panelSimu;
    private JPanel controlSimu;
    private JButton play;
    private JButton stop;
    private JButton pause;
    private ControllerSimulation c;
    private JLabel label_nb_fourmis, label_nb_fourmis_moyen, label_quantite_nourriture;
    private int nb_fourmis, nb_fourmis_total, nb_fourmis_moyen, quantite_nourriture, nb_ticks;
    private ArrayList<Integer> list_nb_fourmis, list_nb_fourmis_moyen, list_quantite_nourriture;
    private JList myList;
    private JScrollPane js;
    private JPanel legende;
	private JButton statsbutton;
	private JCheckBox avanceRapide;

    public VueSimulation(ControllerSimulation c) {
        super("Simulation");
        this.c = c;
        this.c.setVueSimulation(this);
        setSize(800, 600);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // Stats
        this.nb_fourmis = 0;
        this.nb_fourmis_moyen = 0;
        this.quantite_nourriture = 0;
        this.nb_fourmis_total = 0;
        this.nb_ticks = 0;

        init();
        
        this.updateStats();
        setVisible(true);
    }

    private void init() {
        panelSimu = new PanelCarte(c.getCarte());
        panelSimu.setBorder(BorderFactory.createLineBorder(Color.black));
        controlSimu = new JPanel();
        SimuListener sl = new SimuListener(this);
        JPanel centerControlSimu = new JPanel();
        ArrayList<String> data = parsefichier();
        myList = new JList(data.toArray());
        myList.setCellRenderer(new WhiteYellowCellRenderer());
        js = new JScrollPane(myList);
        js.setBorder(BorderFactory.createLineBorder(Color.black));

        js.setPreferredSize(new Dimension(300, 0));
        
        avanceRapide=new JCheckBox("Avance rapide");
        controlSimu.setLayout(new GridLayout(1, 3));
        try {
            play = new JButton(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/play.png"))));
            pause = new JButton(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/pause.png"))));
            stop = new JButton(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/stop.png"))));

            play.setOpaque(false);
            play.setContentAreaFilled(false);
            play.setBorderPainted(false);
            pause.setOpaque(false);
            pause.setContentAreaFilled(false);
            pause.setBorderPainted(false);
            stop.setOpaque(false);
            stop.setContentAreaFilled(false);
            stop.setBorderPainted(false);
            stop.setEnabled(false);

        } catch (IOException e) {
            // TODO Bloc catch auto-généré
            FourmizLogger.warn(this, e);
            JOptionPane.showMessageDialog(this, "Impossible de charger les images");
        }

        play.setActionCommand("play");
        pause.setActionCommand("pause");
        stop.setActionCommand("stop");
        play.addActionListener(sl);
        pause.addActionListener(sl);
        stop.addActionListener(sl);
        this.addWindowListener(sl);

        centerControlSimu.add(play);
        centerControlSimu.add(pause);
        centerControlSimu.add(stop);

        JLabel label_blue = new JLabel("    Fourmie sur le retour");
        label_blue.setOpaque(true);
        label_blue.setBackground(Color.BLUE);
        JLabel label_cyan = new JLabel("    Fourmilliere");
        label_cyan.setOpaque(true);
        label_cyan.setBackground(Color.CYAN);
        JLabel label_orange = new JLabel("    Pheromones");
        label_orange.setOpaque(true);
        label_orange.setBackground(Color.ORANGE);
        JLabel label_yellow = new JLabel("    Nourriture");
        label_yellow.setOpaque(true);
        label_yellow.setBackground(Color.YELLOW);
        JLabel label_pink = new JLabel("    Suiveuse");
        label_pink.setOpaque(true);
        label_pink.setBackground(Color.MAGENTA);
        JLabel label_gray = new JLabel("    Roche");
        label_gray.setOpaque(true);
        label_gray.setBackground(Color.GRAY);
        JLabel label_red = new JLabel("    Eclaireuse");
        label_red.setOpaque(true);
        label_red.setBackground(Color.RED);
        JLabel label_green = new JLabel("    Herbe");
        label_green.setOpaque(true);
        label_green.setBackground(Color.GREEN);

        GridLayout gridLegend = new GridLayout(2, 4);
        this.legende = new JPanel();
        this.legende.setLayout(gridLegend);
        this.legende.add(label_blue);
        this.legende.add(label_cyan);
        this.legende.add(label_orange);
        this.legende.add(label_yellow);
        this.legende.add(label_pink);
        this.legende.add(label_gray);
        this.legende.add(label_red);
        this.legende.add(label_green);
        
        list_nb_fourmis=new ArrayList<Integer>();
        list_nb_fourmis_moyen=new ArrayList<Integer>();
        list_quantite_nourriture=new ArrayList<Integer>();
        
        try {
			statsbutton=new JButton(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/stats.png"))));
		} catch (IOException e) {
			statsbutton=new JButton("Statistiques");
			e.printStackTrace();
		}
        statsbutton.setActionCommand("stats");
        statsbutton.addActionListener(sl);
        
        avanceRapide.setActionCommand("avance");
        avanceRapide.addActionListener(sl);
        controlSimu.setLayout(new BorderLayout());
            
        
        controlSimu.add(legende, BorderLayout.SOUTH);
        controlSimu.add(statsbutton,BorderLayout.EAST);
        controlSimu.add(avanceRapide,BorderLayout.WEST);
        controlSimu.add(centerControlSimu, BorderLayout.CENTER);

        JPanel nord = new JPanel(new GridLayout(1, 3));
        this.label_nb_fourmis = new JLabel("", JLabel.CENTER);
        this.label_nb_fourmis_moyen = new JLabel("", JLabel.CENTER);
        this.label_quantite_nourriture = new JLabel("", JLabel.CENTER);

        nord.add(this.createStat(label_nb_fourmis, 0, "Nombre de fourmis"));
        nord.add(this.createStat(label_nb_fourmis_moyen, 0, "Nombre de fourmis moyen"));
        nord.add(this.createStat(label_quantite_nourriture, 0, "Quantité de nourriture"));

        add(nord, BorderLayout.NORTH);
        add(panelSimu, BorderLayout.CENTER);
        add(controlSimu, BorderLayout.PAGE_END);
        add(js, BorderLayout.EAST);
    }

    public void updateStats() {
        this.nb_ticks++;

        int current_fourmis = 0;
        int current_nourriture = 0;

        for (Element e : this.c.getCarte().getElements()) {
            if (e instanceof Fourmiliere) {
                current_fourmis += ((Fourmiliere) e).getFourmis().size();
            } else if (e instanceof Nouriturre) {
                current_nourriture += ((Nouriturre) e).getQuantiteNourritureDisponible();
            }
        }

        this.nb_fourmis = current_fourmis;
        list_nb_fourmis.add(nb_fourmis);
        this.nb_fourmis_total += this.nb_fourmis;
        this.nb_fourmis_moyen = this.nb_ticks == 0 ? current_fourmis : this.nb_fourmis_total / this.nb_ticks;
        list_nb_fourmis_moyen.add(nb_fourmis_moyen);
        this.quantite_nourriture = current_nourriture;
        list_quantite_nourriture.add(quantite_nourriture);

        this.label_nb_fourmis.setText("" + this.nb_fourmis);
        
        this.label_nb_fourmis_moyen.setText("" + this.nb_fourmis_moyen);
        this.label_quantite_nourriture.setText("" + this.quantite_nourriture);
        
        
        this.nb_ticks++;
    }

    private JPanel createStat(JLabel champs, int nombre, String description) {
        JLabel desc = new JLabel(description, JLabel.CENTER);
        JPanel stat = new JPanel(new BorderLayout());

        champs.setText("" + nombre);
        Font labelFont = champs.getFont();

        champs.setFont(new Font(labelFont.getName(), Font.BOLD, 15));

        stat.add(champs, BorderLayout.SOUTH);
        stat.add(desc, BorderLayout.CENTER);

        return stat;
    }

    private ArrayList<String> parsefichier() {
        ArrayList<String> chaine = new ArrayList<>();
        String fichier = "sample.log";

        //lecture du fichier texte	
        try {

            InputStreamReader ipsr = new InputStreamReader(new FileInputStream(fichier), "UTF8");
            BufferedReader br = new BufferedReader(ipsr);
            String ligne;
            while ((ligne = br.readLine()) != null) {
                String level = ligne.split("\\[")[1].split(" ")[1];

                if (level.contains("INFO")) {
                    String[] message = ligne.split("-");
                    String mess = message[message.length - 1];
                    chaine.add(mess);
                }
            }
            br.close();
        } catch (IOException e) {
            FourmizLogger.error(this, e);
        }
        
        
        return chaine;
    }

    public void setData() {
        ArrayList<String> data = parsefichier();
        myList = new JList(data.toArray());
        js.setViewportView(myList);
        js.revalidate();
        js.repaint();
    }

    public ControllerSimulation getC() {
        return c;
    }

    public JButton getPlay() {
        return play;
    }

    public JButton getStop() {
        return stop;
    }

    public JButton getPause() {
        return pause;
    }

    private static class WhiteYellowCellRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (index % 2 == 0) {
                c.setBackground(Color.lightGray);
            } else {
                c.setBackground(Color.gray);
            }
            return c;
        }
    }

	public ArrayList<Integer> getList_nb_fourmis() {
		return list_nb_fourmis;
	}

	public void setList_nb_fourmis(ArrayList<Integer> list_nb_fourmis) {
		this.list_nb_fourmis = list_nb_fourmis;
	}

	public ArrayList<Integer> getList_nb_fourmis_moyen() {
		return list_nb_fourmis_moyen;
	}

	public void setList_nb_fourmis_moyen(ArrayList<Integer> list_nb_fourmis_moyen) {
		this.list_nb_fourmis_moyen = list_nb_fourmis_moyen;
	}

	public ArrayList<Integer> getList_quantite_nourriture() {
		return list_quantite_nourriture;
	}

	public void setList_quantite_nourriture(
			ArrayList<Integer> list_quantite_nourriture) {
		this.list_quantite_nourriture = list_quantite_nourriture;
	}
    
    

}
